package com.dyz.leetcode._03_mathematics;

public class _7_reverse {
    public int reverse(int x) {
        int res = 0;
        while(x!=0){
            int pop = x%10;
            x = x/10;
            //判断是否溢出
            if(res>Integer.MAX_VALUE/10 || (res==Integer.MAX_VALUE/10 && pop>7)){return 0;}
            if(res<Integer.MIN_VALUE/10 || (res==Integer.MIN_VALUE/10 && pop<-8)){return 0;}
            res = res*10+pop;
        }
        return res;
    }

    public int reverse1(int x) {
        //方法二 溢出后判断
        int res = 0;
        while (x!=0){
            int pop = x%10;
            x = x/10;
            int newRes = res*10+pop;
            if ((newRes - pop) / 10 != res) return 0;
            res = newRes;
        }
        return res;
    }

    public int reverse2(int x) {
        String str = String.valueOf(x);
        char[] chars = str.toCharArray();
        int left = 0, right = chars.length-1;
        if (chars[left] < '0' || chars[left] > '9') left++;
        while (left < right) {
            char tmp = chars[left];
            chars[left] = chars[right];
            chars[right] = tmp;
            left++;
            right--;
        }
        // 如果反转后，数据溢出的话
        long res = Long.parseLong(new String(chars));
        if(res>Integer.MAX_VALUE || res<Integer.MIN_VALUE){return 0;}
        return (int) res;
    }


    public static void main(String[] args) {
        System.out.println(-71/10);
    }
}
